package com.travel.Controller;

import com.github.pagehelper.PageInfo;
import com.travel.Bean.Ticket;

import com.travel.JPA.CultureJPA;
import com.travel.JPA.TicketJPA;
import com.travel.Pojo.TicketAndCultureName;
import com.travel.Service.Impl.TicketServiceImpl;
import com.travel.util.ConsoleOutputControl;
import com.travel.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Api("项目Ticket页面控制类")
@RestController
@RequestMapping("/SuperTicket")
public class SuperTicketController {

    @Autowired
    private TicketServiceImpl ticketService;
    @Autowired
    private CultureJPA cultureJPA;
    @Autowired
    private TicketJPA ticketJPA;
    //获取管理员权限信息
    public String getAdminRole() {
        String role;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            role = ((UserDetails) principal).getAuthorities().toString();
        } else {
            role = principal.toString();
        }
        return role;
    }

    //获取管理员名称
    public String getUsername() {
        String username;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }



    @ApiOperation("项目页面")
    @GetMapping("/TicketPage")
    public ModelAndView TicketPage(){
        return new ModelAndView("public/TicketPage");
    }

    @ApiOperation("项目列表")
    @PostMapping("/TicketList")
    public R TicketList(String ticketName, @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "15") Integer limit){

        Integer cultureId = null;
        if(getAdminRole().equals("super"))
             cultureId = Integer.parseInt(cultureJPA.findCultureIdByUsername(getUsername()).toString());

        PageInfo<TicketAndCultureName> ticketAndCultureNamePageInfo = ticketService.selTicketList(ticketName,cultureId,page,limit,true);

        return R.ok("0",ticketAndCultureNamePageInfo.getList(),ticketAndCultureNamePageInfo.getTotal());

    }

    private void deleteSession(HttpSession session){
        if(null != session.getAttribute("imgsPath"))
            session.removeAttribute("imgsPath");
    }

    @ApiOperation("添加项目页面")
    @GetMapping("/TicketAddPage")
    public ModelAndView TicketAdd(HttpSession session){
        //清空Ticket图片session
        deleteSession(session);
        return new ModelAndView("public/TicketAdd");
    }

    @ApiOperation("编辑项目页面")
    @GetMapping("/TicketEditPage")
    public ModelAndView TicketEdit(Integer id,HttpSession session){
        //清空Ticket图片session
        deleteSession(session);

        ModelAndView modelAndView = new ModelAndView("public/TicketEdit");
        //Ticket图片Map
        Map<String,String> imgsPath = new HashMap<>();
        //Ticket图片数量
        int imgNum = 0;
        //通过景区id获取信息
        Ticket ticket = ticketService.getTicketById(id);
        if(ticket.getTicket_imgs() == null){
            ticket.setTicket_imgs(" ");
        }else{
            /*将保存的JSON格式图片信息，转换为map存入session，便于之后的项目编辑*/
            String [] b1 = ticket.getTicket_imgs().split(",");
            for (int i = 0;i<b1.length-1;i+=2){
                String name = b1[i].substring(b1[i].indexOf("'")+1,b1[i].lastIndexOf("'"));
                String url = b1[i+1].substring(b1[i+1].indexOf("'/")+1,b1[i+1].lastIndexOf("'"));
                imgsPath.put(name,url);
            }
            imgNum = (b1.length-1)/2;
            //Ticket的图片信息存入session
            session.setAttribute("imgNum",imgNum);
            session.setAttribute("imgsPath",imgsPath);
        }
        modelAndView.addObject("ticket",ticket);
        return modelAndView;
    }


    @ApiOperation("删除上传的图片")
    @PostMapping("TicketDelImgs")
    public R TicketDelImgs(String filename,HttpSession session){
        try{
            Map<String,String> SimgsPath = (Map<String, String>) session.getAttribute("imgsPath");
            int SimgNum = (int) session.getAttribute("imgNum");
            SimgNum -= 1;
            SimgsPath.remove(filename);
            session.setAttribute("imgNum",SimgNum);
            session.setAttribute("imgsPath",SimgsPath);
        }catch (Exception e){
            e.printStackTrace();
            return R.no(1);
        }


        return R.ok(0);
    }


    /**
     * 保存项目
     *
     * @param ticket  项目
     * @param session 会话
     * @return {@link R}
     */
    @ApiOperation("保存项目内容")
    @PostMapping("/saveTicket")
    public R saveTicket(Ticket ticket, HttpSession session){
        /*从session中取出保存的图片信息*/
        Map<String,String> S_ticket_imgs = (Map<String, String>) session.getAttribute("imgsPath");
        /*从session中移除无用的信息，防止后续保存异常*/
        session.removeAttribute("imgsPath");
        session.removeAttribute("imgNum");
        /*将文件名和访问地址拼接成JSON字符串保存
        * 后续前端回显使用的时候还是在前端作为普通字符串拼接后使用的*/
        if(S_ticket_imgs != null){
            StringBuilder imgsPath = new StringBuilder();
            for (Map.Entry<String,String> entry : S_ticket_imgs.entrySet()){
                imgsPath.append("{name:'").append(entry.getKey()).append("',url:'").append(entry.getValue()).append("'},");
            }

            ticket.setTicket_imgs(imgsPath.toString());
        }

        int res = 1;

       //如果是添加新的项目，需要填入当前用户代表的景区id
        if(ticket.getCulture_id() == null){
            ticket.setCulture_id(cultureJPA.findCultureIdByUsername(getUsername()).get(0));
            res = ticketService.saveAddTicket(ticket, String.valueOf(getAdminRole().equals("super")?0:null));
        }else
            res = ticketService.saveEditTicket(ticket);
        //失败返回1成功返回0
        return R.ok(res);
    }


    /**
     * 设置项目不可见--管理员
     *
     * @param ids id
     * @return {@link R}
     */
    @ApiOperation("删除项目")
    @PostMapping("/DelTicket")
    public R DelTicket(Integer[] ids){
        //获取当前管理员的所在的景区的id
        Integer cultureId =cultureJPA.findCultureIdByUsername(getUsername()).get(0);
        int idNum = ids.length;
        int res = ticketService.deleteTicket(ids,String.valueOf(getAdminRole().equals("super")?0:null),cultureId);

        if(idNum == res)
            return R.ok(0);

        return R.no(1,"成功；“"+res+"”,失败：“"+(idNum-res)+"”");
    }

    /**
     * 更新项目启用用户
     * 修改项目可见--用户
     *
     * @param ticketId 项目id
     * @return {@link R}
     */
    @ApiOperation("设置用户是否可见Ticket")
    @ApiResponses({
            @ApiResponse(code = 1,message = "用户--不可见"),
            @ApiResponse(code = 0,message = "用户--可见"),
            @ApiResponse(code = -1,message = "设置失败")
    })

    @PostMapping("/updateTicketEnable_user")
    public R updateTicketEnable_user(Integer ticketId){
        try{
            Integer cultureId = ticketService.findCultureIdByTicketId(ticketId);
            if(ticketService.findEnable_userByTicketId(ticketId) == 0)
                if(ticketService.hideTicket_User(ticketId,cultureId)>0){
                    return R.ok(1,"用户--不可见");
                }
                else
                if(ticketService.recoveryTicket_User(ticketId,cultureId)>0)
                    return R.ok(0,"用户--可见");
        }catch (Exception e){
            e.printStackTrace();
            ConsoleOutputControl.getOutputString_33("updateTicketEnable_user error");
            return R.no(-1,"设置失败");
        }

        return null;
    }


}
